package com.prestamomo.vil.ppa.pmvilmedium;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.prestamomo.vil.ppa.PmvilApp;
import com.prestamomo.vil.ppa.pmvilapi.PmvilUtilize;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PmvilAppInfoMd {

    public static PmvilUtilize getAppPmvilInfo(){
        PmvilUtilize pmvilUtilize = new PmvilUtilize();
        List<PmvilUtilize.AppListPmvil> pmvilUtilizeList = new ArrayList<>();
        PackageManager pmvilPagManager = PmvilApp.getPmvilApss().getPackageManager();
        List<PackageInfo> pmvilInstalledPages = pmvilPagManager.getInstalledPackages(0);
        for (PackageInfo pmvilPagInfo : pmvilInstalledPages) {
            if(TextUtils.isEmpty(pmvilPagInfo.applicationInfo.loadLabel(pmvilPagManager).toString())) {
                continue;
            }else{
                PmvilUtilize.AppListPmvil utilizeListPmvil = new PmvilUtilize.AppListPmvil();
                boolean pmvilIsSysApp = (pmvilPagInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
                boolean pmvilIsSysUpd = (pmvilPagInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
                boolean pmvilIsSystem = pmvilIsSysApp || pmvilIsSysUpd;

                utilizeListPmvil.setQnvbvhi(pmvilIsSystem?0:1);//app_type
                utilizeListPmvil.setHmntbss( pmvilPagInfo.applicationInfo.loadLabel(pmvilPagManager).toString());//app_name
                utilizeListPmvil.setIjfjhkdqf(pmvilPagInfo.packageName);//package_name
                utilizeListPmvil.setQtckrbayv(pmvilPagInfo.versionName);//version_name
                utilizeListPmvil.setOnujiy(pmvilPagInfo.applicationInfo.flags);//flags
                utilizeListPmvil.setBuaacip( pmvilPagInfo.versionCode);//version_code

                try {
                    ApplicationInfo pmvilAppInfo = pmvilPagManager.getApplicationInfo(pmvilPagInfo.packageName, 0);
                    String pmvilAppFile = pmvilAppInfo.sourceDir;
                    long pmvilInstalled = new File(pmvilAppFile).lastModified();
                    utilizeListPmvil.setZpttgb(pmvilInstalled);//in_time
                    if (pmvilPagInfo.lastUpdateTime <= 0) {
                        utilizeListPmvil.setUcocknx(pmvilInstalled);//up_time
                    } else {
                        utilizeListPmvil.setUcocknx(pmvilPagInfo.lastUpdateTime);//up_time
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    utilizeListPmvil.setZpttgb(pmvilPagInfo.firstInstallTime);//in_time
                    utilizeListPmvil.setUcocknx(pmvilPagInfo.lastUpdateTime);//up_time
                }
                pmvilUtilizeList.add(utilizeListPmvil);
            }

        }
        pmvilUtilize.setNqutd(pmvilUtilizeList);
       return pmvilUtilize;
    }
}
